"use strict";

var Q = require('q'),
    fs = require('fs'),
    path = require('path'),
    mailer = require("./core/mailerservice"),
    mustache = require("./core/mustacheservice");


function EmailService() {
    console.log("EmailService constructor");
    this.text = {
        validation: this.readFileSync("./email/validation/validation.txt").toString(),
        recovery: this.readFileSync("./email/recovery/recovery.txt").toString()
    };

    this.html = {
        validation: this.readFileSync("./email/validation/validation.html").toString(),
        recovery: this.readFileSync("./email/recovery/recovery.html").toString()
    };
}

EmailService.prototype.readFileSync = function(filename){
    return fs.readFileSync(path.join(__dirname, filename));
}

EmailService.prototype.sendValidation = function (token, user) {
    var self = this;
    if (!token) throw new Error("token is not defined.");
    if (!user) throw new Error("user is not defined.");

    var view = {
        token: token,
        user: user
    };

    return mustache.render(self.text.validation, view).then(function (text) {
        return mustache.render(self.html.validation, view).then(function (html) {
            return mailer.send("Activation de votre compte", user.contact.email, text, html);
        });
    });
};

EmailService.prototype.sendRecovery = function (user) {
    var self = this;
    if (!user) throw new Error("user is not defined.");

    var view = {
        user: user
    };

    return mustache.render(self.text.recovery, view).then(function (text) {
        return mustache.render(self.html.recovery, view).then(function (html) {
            return mailer.send("Mot de passe de votre compte", user.contact.email, text, html);
        });
    });
};

exports = module.exports = new EmailService();